<template>
    <div>
        <el-dialog v-model="props.isShow" :title="props.isAdd ? '添加角色' : '编辑角色'" center :before-close="beforeClose">
            <el-form :model="roleForm" ref="roleRef" :rules="rules">
                <el-form-item label="角色名称" :label-width="formLabelWidth" prop="rolename">
                    <el-input v-model="roleForm.rolename" autocomplete="off" />
                </el-form-item>
                <el-form-item label="角色权限" :label-width="formLabelWidth">
                    <el-tree ref="treeRef" :data="store.getters['menu/getMenuList']" show-checkbox default-expand-all
                        :check-strictly="true" node-key="id" highlight-current :props="{
                            children: 'children',
                            label: 'title',
                        }" />
                </el-form-item>
                <el-form-item label="状态" :label-width="formLabelWidth">
                    <el-switch v-model="roleForm.status"
                        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" :active-value="1"
                        :inactive-value="2" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="cancel(roleRef)">取消</el-button>
                    <el-button type="primary" @click="confirm(roleRef)">
                        确定
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
<script lang='ts' setup>
import { reactive, ref, defineProps, defineEmits, defineExpose } from 'vue';
import type { FormInstance, FormRules } from 'element-plus';
import { ElTree, ElMessage } from 'element-plus';
import { useStore } from 'vuex';
import { roleadd, roleedit, roleinfo } from '../../request/api';

import type Node from 'element-plus/es/components/tree/src/model/node'
import role from '@/store/modules/role';
// 调用仓库方法
let store = useStore();

// 定义树形接口
interface Tree {
    id: number
    label: string
    children?: Tree[]
}
// 定义树形规则
const treeRef = ref<InstanceType<typeof ElTree>>();

// 定义ref规则
const roleRef = ref<FormInstance>()
const formLabelWidth = '140px'
const roleForm = ref({
    rolename: '',//角色名称string
    menus: '',//角色权限 id数组'2,3,4' 字符串
    status: 1,//状态1正常2禁用number
})

// 处理角色管理数据
if (store.getters['menu/getMenuList'].length == 0) {
    store.dispatch('menu/getMenulistActions')
}

// 表单验证规则
const rules = reactive<FormRules>({
    rolename: [
        { required: true, message: '请填写角色名称', trigger: 'blur' },
        { min: 2, max: 6, message: '长度在2-6个字符', trigger: 'blur' },
    ]
})

// 接收父组件传值
let props = defineProps({
    isAdd: Boolean,
    isShow: Boolean
})

// 使用defineEmits
let emit = defineEmits(['cancel']);

// 点击x号关闭弹窗
const beforeClose = (done: any) => {
    done();
    // 关闭弹窗
    cancel(roleRef.value)
}

// 点击取消  关闭弹窗  清空表单,规则验证
const cancel = (formEl: FormInstance | undefined) => {
    // 通知父组件关闭
    emit('cancel');
    if (!formEl) return;
    // 清空表单
    roleForm.value = {
        rolename: '',//角色名称string
        menus: '',//角色权限 id数组'2,3,4' 字符串
        status: 1,//状态1正常2禁用number
    }
    // 清空表单规则验证
    formEl.resetFields();

    // 清空tree节点
    treeRef.value!.setCheckedKeys([], false)
}

let newId = 0;

// 数据回显
const lookup = (id: number) => {
    console.log('回显', id);
    roleinfo({ id }).then((res: any) => {
        if (res.code == 200) {
            console.log(res.list);
            roleForm.value = res.list
            newId = id;
            // 转换menus格式
            treeRef.value!.setCheckedKeys(roleForm.value.menus ? roleForm.value.menus.split(',') : [])

        }
    })
}

// 点击确定 
const confirm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate(val => {
        if (val) {
            console.log(roleForm.value,'表单');
            // treeRef.value!.getCheckedKeys()  获取选中的id  array类型
                // 处理数据格式  转换成string
                roleForm.value.menus = treeRef.value!.getCheckedKeys().join();
            if (props.isAdd) {
                // 添加
                
                roleadd(roleForm.value).then(res => {
                    if (res.code == 200) {
                        // 添加成功
                        ElMessage.success(res.msg);
                        // 关闭弹窗
                        cancel(roleRef.value);
                        // 重新渲染视图
                        store.dispatch('role/getRoleListActions');
                    }
                })
            } else {
                // 编辑            
                roleedit({ ...roleForm.value, id: newId }).then(res => {
                    if (res.code == 200) {
                        // 编辑成功
                        ElMessage.success(res.msg);
                        // 关闭弹窗
                        cancel(roleRef.value);
                        // 重新渲染视图
                        store.dispatch('role/getRoleListActions');
                    } else {
                        // 编辑失败
                        ElMessage.error(res.msg)
                    }
                })
            }
        }
    })
}

// 将数据回显暴露出去
defineExpose({
    lookup
})
</script>
<style scoped lang='less'></style>